const userModel = require("../models/userModel");
const encryption = require("../utils/encryption");
const jwt = require("../utils/jwt");

module.exports = {
  // 创建用户（注册）
  async createUser(user) {
    const password = user.password;
    delete user.password;
    user.passwordHash = await encryption.hashPassword(password);
    const response = await userModel.create(user);

    return {
      data: response,
    };
  },

  // 查询单个用户通过手机号（登录）
  async getUserByPhone(phone, password) {
    const user = await userModel.findOne({
      phone,
    });

    const flag = await encryption.comparePassword(password, user.passwordHash);

    if (!flag) {
      throw new Error("密码错误");
    } else {
      delete user.passwordHash;
      const token = jwt.generateToken({
        id: user._id,
        username: user.username,
        createTime: new Date(),
      });
      return {
        token,
        data: user,
      };
    }
  },

  // 更新用户信息
  async updateUser(user) {
    const password = user.password;
    delete user.password;
    user.passwordHash = await encryption.hashPassword(password);
    const message = await userModel.updateOne({ phone: user.phone }, user);
    const data = await userModel.findOne({ phone: user.phone });
    return {
      message,
      data,
    };
  },

  // 查询所有用户
  async getAllUser() {
    return await userModel.find();
  },

  // 删除用户
  async deleteUser(id) {
    const response = await userModel.deleteOne({ _id: id });
    return {
      data: response,
    };
  },
};
